from sqlalchemy import insert, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.utils.date_time import get_date_time
from app.database.models import Statistics, User


async def update_stats(
    session: AsyncSession,
    accounts: int = 0,
    likes: int = 0,
    comments: int = 0,
    documents: int = 0,
    uniques: int = 0,
    whitepages: int = 0,
    dolphin_accs: int = 0,
    wlo_accs: int = 0,
    messages_distribution: int = 0,
) -> None:

    date = get_date_time(get_datetime=True).date()

    try:
        await session.execute(
            insert(Statistics).values(
                days=date,
                accounts=accounts,
                likes=likes,
                comments=comments,
                documents=documents,
                uniques=uniques,
                whitepages=whitepages,
                dolphin_accs=dolphin_accs,
                wlo_accs=wlo_accs,
                messages_distribution=messages_distribution,
            )
        )
    except IntegrityError:
        await session.execute(
            update(Statistics)
            .where(Statistics.days == date)
            .values(
                accounts=Statistics.accounts + accounts,
                likes=Statistics.likes + likes,
                comments=Statistics.comments + comments,
                documents=Statistics.documents + documents,
                uniques=Statistics.uniques + uniques,
                whitepages=Statistics.whitepages + whitepages,
                dolphin_accs=Statistics.dolphin_accs + dolphin_accs,
                wlo_accs=Statistics.wlo_accs + wlo_accs,
                messages_distribution=Statistics.messages_distribution
                + messages_distribution,
            )
        )
    await session.commit()


async def update_user_stats(
    session: AsyncSession,
    telegram_id: int,
    accounts_added: int = 0,
    likes: int = 0,
    comments: int = 0,
    uniques: int = 0,
    documents_generated: int = 0,
    whitepages_generated: int = 0,
    dolphin_accs_loaded: int = 0,
    wlo_accs_reged: int = 0,
) -> None:

    q = (
        update(User)
        .where(User.telegram_id == telegram_id)
        .values(
            accounts_added=User.accounts_added + accounts_added,
            likes=User.likes + likes,
            comments=User.comments + comments,
            uniques=User.uniques + uniques,
            documents_generated=User.documents_generated + documents_generated,
            whitepages_generated=User.whitepages_generated + whitepages_generated,
            dolphin_accs_loaded=User.dolphin_accs_loaded + dolphin_accs_loaded,
            wlo_accs_reged=User.wlo_accs_reged + wlo_accs_reged,
        )
    )

    await session.execute(q)

    await session.commit()
